import { ElMessage } from "element-plus"
import router from "./router"
import { useUserStore } from "./stores/user"
import { getProfileAPI } from "./apis/user"
import type { RouteRecordRaw } from "vue-router"
import { asyncRoutes } from "./router/asyncRoutes";
import { useMenuStore } from "./stores/menu";


//路由白名单
const WHITE_LIST = ["/login","/404"]

//处理一级路由数据
const getFirstRoutePerms = (permissions: string[]) => {
  // 提取一级路由菜单
  const tempArr = permissions.map((item) => item.split(':')[0])
  // 数组去重
  return Array.from(new Set(tempArr))
}

// 处理二级路由权限数据
const getSecondRoutePerms = (permsArr: string[]) => {
  const newArr = permsArr.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return Array.from(new Set(newArr))
}




// 根据权限筛选出匹配的路由
const getRoutes = (
  firstRoutePerms: string[],  // 一级路由权限集合
  secondRoutePerms: string[], // 二级路由权限集合
  asyncRoutes: RouteRecordRaw[] // 所有的动态路由数据
) => {
  console.log(firstRoutePerms, secondRoutePerms, asyncRoutes);
  //超级管理员，不做筛选，返回所有的路由信息
  if(firstRoutePerms.includes('*')){
    return [...asyncRoutes]
  }

  // 过滤出一级路由
  const firstRoutes = asyncRoutes.filter(route => {
    return firstRoutePerms.includes(route.meta!.permission!)
  })
  // 基于筛选的一级路由，继续筛选二级路由
  const lastRoutes = firstRoutes.map(route => {
    return {
      ...route,
      // 筛选二级路由
      children: route.children?.filter(v=> secondRoutePerms.includes(v.meta!.permission!))
    }
  })
  return lastRoutes
}





//路由导航守卫
router.beforeEach(async(to,from,next)=>{
  const store =  useUserStore()
  //判断是否有token
  if(store.token){
    // next()
    if(!store.profile.id){
      const res = await getProfileAPI()
      store.setProfile(res.data)
      console.log('profile res', res);
      const menus = getFirstRoutePerms(res.data.permissions)
      const smenus = getSecondRoutePerms(res.data.permissions)
      // console.log('menus', menus);
      // console.log('smenus', smenus);
      // getRoutes(menus, smenus, asyncRoutes)
      // const lastRoutes = getRoutes(menus, smenus, asyncRoutes)
      // console.log('lastRoutes', lastRoutes);
      // 1. 获取匹配的路由
      const perRoutes = getRoutes(menus, smenus, asyncRoutes)
      //2.遍历匹配的路由，动态添加路由
      perRoutes.forEach(route =>{
         // 动态添加路由
        router.addRoute(route as RouteRecordRaw)
      })

       // 3. 保存侧栏菜单路由
       const menuStore = useMenuStore()
       menuStore.setMenuList(perRoutes as RouteRecordRaw[])

      // 动态添加路由后的固定用法
      next({...to})
    }else {
      // 有 token，放行
      next()
    }
  }else{
    //判断是否在白名单中
    if(WHITE_LIST.includes(to.path)){
      next()
    }else{
      ElMessage.warning("请先登录")
      next("/login")
    }

  }
})